package com.example.geckohurricanes;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {

	private boolean val = false;
	private EditText loginname, loginpass;
	private int counter = 0;
	public String user, pass;
	Toast toast;
	public User loginAttempt;
	private static final String TABLE_LOGIN = "login";
	String ret;
	AlertDialog dialog;
	public int numid, locked = 0;
	List<Contact> contacts;
	DatabaseHandler db;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		//Filling in instance fields
		loginname = (EditText) findViewById(R.id.uname);
		loginpass = (EditText) findViewById(R.id.pword);
		Button login = (Button) findViewById(R.id.btnLogin);
		TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
		db = new DatabaseHandler(this);
		
		//Basic Contact
		Log.d("Insert: ", "Inserting ..");
        db.addContact(new Contact("admin", "admin", 1));
        Log.d("Reading: ", "Reading all contacts..");
        contacts = db.getAllContacts();       
        for (Contact cn : contacts) {
            String log = "Id: "+cn.getId()+", Name: " + cn.getName() + ", Pass: " + cn.getPass();
            Log.d("Name: ", log);
        }
		
		//If you want to go to the register page
		registerScreen.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent a = new Intent(getApplicationContext(), RegisterActivity.class);
				startActivity(a);
				db.close();
				finish();
			}
		});
		
		//If you want to login
		login.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				user = loginname.getText().toString();
				pass = loginpass.getText().toString();
				Contact c = new Contact(user, pass);
				
				for (Contact cn : contacts) {
					if (cn.equals(c)) {
						val = true;
						break;
					}
				}
				
				if(val) {
					Intent b = new Intent(getApplicationContext(), HomePageActivity.class);
					Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
					startActivity(b);
					db.close();
					finish();
				} else {
					Toast.makeText(getApplicationContext(), "Failed, try again or register.", Toast.LENGTH_SHORT).show();
					locked++;
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

}
